package com.nettyBasic.n6_embeddedChannel;

import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.channel.embedded.EmbeddedChannel;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;

/**
 * @author： pang-yun
 * @date： 2021-09-13 15:40
 * 功能目的 ：用于  netty 提供的一个专门用来测试处理器效果的测试类： EmBeddedChannel
 */
@Slf4j
public class EmbeddedChannelDemo {
    public static void main(String[] args) {
        ChannelInboundHandlerAdapter i1 = new ChannelInboundHandlerAdapter(){
            @Override
            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                log.info("1");
                super.channelRead(ctx, msg);
            }
        };
        ChannelInboundHandlerAdapter i2 = new ChannelInboundHandlerAdapter(){
            @Override
            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                log.info("2");
                super.channelRead(ctx, msg);
            }
        };
        ChannelInboundHandlerAdapter i3 = new ChannelInboundHandlerAdapter(){
            @Override
            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                log.info("3");
                super.channelRead(ctx, msg);
            }
        };
        ChannelOutboundHandlerAdapter o1 = new ChannelOutboundHandlerAdapter(){
            @Override
            public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
                log.info("o1");
                super.write(ctx, msg, promise);
            }
        };
        ChannelOutboundHandlerAdapter o2 = new ChannelOutboundHandlerAdapter(){
            @Override
            public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
                log.info("o2");
                super.write(ctx, msg, promise);
            }
        };
        ChannelOutboundHandlerAdapter o3 = new ChannelOutboundHandlerAdapter(){
            @Override
            public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
                log.info("o3");
                super.write(ctx, msg, promise);
            }
        };
        //-------------------------------------------
        EmbeddedChannel embeddedChannel = new EmbeddedChannel(i1, i2, i3, o1, o2, o3);
        //1. 模拟入站操作
        embeddedChannel.writeInbound(ByteBufAllocator.DEFAULT.buffer().writeBytes("embeddedChannel".getBytes()));
        //2. 模拟出站操作
        embeddedChannel.writeOneOutbound(ByteBufAllocator.DEFAULT.buffer().writeBytes("out".getBytes(StandardCharsets.UTF_8)));
    }
}
